/* $Id: Layout.java 137 2011-08-29 20:33:36Z altdotua@gmail.com $ */

package alt.djudge.frontend.client.ui.admin;

import alt.djudge.frontend.client.rpc.DJudgeGWTAdminService;
import alt.djudge.frontend.client.rpc.DJudgeGWTAdminServiceAsync;
import alt.djudge.frontend.client.ui.ContentPage;
import alt.djudge.frontend.client.ui.grids.EditEntryPanel;
import alt.djudge.frontend.shared.dto.admin.AdminDTOEntry;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.VerticalPanel;


public class Layout extends Composite
{
	public static DJudgeGWTAdminServiceAsync adminService = GWT.create(DJudgeGWTAdminService.class);
	
	interface MyUiBinder extends UiBinder<DockLayoutPanel, Layout> {}

	private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);

	private static Layout layout;
	
	public static Layout getLayout()
	{
		return layout;
	}
	
	@UiField
	public ScrollPanel contentPanel;

	ContentPage[] pages;

	@UiField
	public FlowPanel westPanel;

	private final DialogBox dbAjaxLoader;

	@UiField
	public FlowPanel flowPanel;
	
	public Layout()
	{
		initWidget(uiBinder.createAndBindUi(this));

		layout = this;
		
		dbAjaxLoader = createAjaxLoaderDialog();
		
		pages = new ContentPage[flowPanel.getWidgetCount()];
		for (int i = 0; i < pages.length; i++)
			pages[i] = (ContentPage) flowPanel.getWidget(i);
		
		History.addValueChangeHandler(new ValueChangeHandler<String>()
		{
			public void onValueChange(ValueChangeEvent<String> event)
			{
				String historyToken = event.getValue();
				onHistoryEvent(historyToken);
			}
		});
		
		onHistoryEvent(History.getToken());
	}
	
	public void showAjaxLoader()
	{
		dbAjaxLoader.center();
		dbAjaxLoader.show();
	}
	
	public void hideAjaxLoader()
	{
		dbAjaxLoader.hide();
	}

	private DialogBox createAjaxLoaderDialog()
	{
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Подождите, идет загрузка данных");
		dialogBox.setWidget(new Image("/images/ajax-loader.gif"));
		dialogBox.setGlassEnabled(true);
		dialogBox.setAnimationEnabled(true);
		return dialogBox;
	}
	
	public void onHistoryEvent(String historyToken)
	{
		for (ContentPage page : pages)
		{
			page.setVisible(false);
		}

		int cnt = 0;
		for (ContentPage page : pages)
		{
			cnt++;
			String pageToken = page.getHistoryTokenPrefix();
			if (cnt == pages.length || historyToken.startsWith(pageToken))
			{
				page.setVisible(true);
				String restToken = pageToken.length() + 1 <= historyToken.length() ? historyToken.substring(pageToken.length() + 1) : "";
				page.dispatch(restToken);
				return;
			}
		}
	}

	@SuppressWarnings("rawtypes")
	public static DialogBox createEditEntryDialogBox(final EditEntryPanel panel)
	{
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText(panel.fCreate ? "Create entry" : "Edit entry");

		VerticalPanel dialogContents = new VerticalPanel();
		dialogContents.setSpacing(2);
		dialogBox.setWidget(dialogContents);

		dialogContents.add(panel);
		
		final Button btnAddFilter = new Button(panel.fCreate ? "Create" : "Save");
		btnAddFilter.addClickHandler(new ClickHandler()
		{
			@Override
			public void onClick(ClickEvent event)
			{
				int k = panel.entry.dtoEntry.getFieldNames().length;
				String[] fieldValues = new String[k];
				for (int i = 0; i < k; i++)
				{
					fieldValues[i] = panel.getEditor(i).getKey();
				}
				panel.entry.dtoEntry.setData(fieldValues);
				
				AsyncCallback<AdminDTOEntry> callback = new AsyncCallback<AdminDTOEntry>()
				{
					@SuppressWarnings("unchecked")
					@Override
					public void onSuccess(AdminDTOEntry result)
					{
						if (result != null)
						{
    						if (panel.fCreate)
    						{
								panel.entry.grid.receivedData.add(result);
								panel.entry.grid.showDataInGrid();
    						}
    						else
    						{
    							panel.entry.grid.receivedData.set(panel.entry.receivedIndex, result);
    							panel.entry.grid.showDataInGrid();
    						}
    						dialogBox.hide();
						}
						else
						{
							Window.alert("Error");
						}
					}
					
					@Override
					public void onFailure(Throwable caught)
					{
						Window.alert(caught.toString());
						dialogBox.hide();
					}
				};
				
				if (panel.fCreate) 
					adminService.createEntry(panel.entry.dtoEntry, callback);
				else
					adminService.editEntry(panel.entry.dtoEntry, callback);
			}
		});

		Button closeButton = new Button("Cancel");
		closeButton.addClickHandler(new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{
				dialogBox.hide();
			}
		});
		
		HorizontalPanel panelButtons = new HorizontalPanel();
		panelButtons.add(btnAddFilter);
		panelButtons.add(closeButton);
		panelButtons.setSpacing(15);
		dialogContents.add(panelButtons);
		
		return dialogBox;
	}
}
